package com.zz.common.handle;

import com.zz.common.config.Constants;
import com.zz.common.protocol.ProtocolFactory;
import com.zz.common.protocol.TunnelProtocol;
import com.zz.common.protocol.handle.ProtocolHandle;
import com.zz.common.utils.ObjectUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 消息解码处理器
 *
 * @author zz
 */
@Slf4j
public class TunnelProtocolDecode extends LengthFieldBasedFrameDecoder {


    public TunnelProtocolDecode(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    @Override
    protected TunnelProtocol decode(ChannelHandlerContext context, ByteBuf byteBuf) throws Exception {
        ByteBuf decodeBuf = null;
        try {
            decodeBuf = (ByteBuf) super.decode(context, byteBuf);
            if (null == decodeBuf || decodeBuf.readableBytes() < Constants.Numbers.HEADER_SIZE) {
                return null;
            }
            ProtocolHandle protocolHandle = ProtocolFactory.getProtocolHandle();
            return protocolHandle.decode(context, decodeBuf);
        } catch (Exception e) {
            log.info("消息协议解码失败！error:【{}】", e.getMessage());
            return null;
        } finally {
            if (ObjectUtil.isNotNull(decodeBuf)) {
                decodeBuf.release();
            }
        }

    }
}
